<template>
  <div>
    <a-modal v-model:open="open" title="配置菜单" @ok="handleOk" :confirm-loading="loading" :destroy-on-close="true">
      <a-tree
        v-model:checkedKeys="checked"
        :fieldNames="{ children: 'children', title: 'name', key: 'id' }"
        :tree-data="parentOptions"
        checkable
        default-expand-all
        :height="400"
      >
      </a-tree>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, defineEmits } from 'vue'
import { type CreateRoleDto, setRoleMenuApi } from '@/api/role.api.ts'
import { getAllMenuApi, getRoleMenuApi, type MenuDto } from '@/api/menu.api.ts'

const emits = defineEmits(['editOk'])

const open = ref<boolean>(false)
const Record = ref()
const checked = ref<number[] | string[]>([])

const showModal = (record: CreateRoleDto) => {
  open.value = true
  Record.value = { ...record }
  checked.value.length = 0
  loading.value = false
  getParentOptions()
  getChecked()
}

const parentOptions = ref<MenuDto[]>([])
const getParentOptions = () => {
  getAllMenuApi().then((res: MenuDto[]) => {
    parentOptions.value = res
  })
}

const getChecked = () => {
  getRoleMenuApi(Record.value.id).then((res) => {
    checked.value = res ?? []
  })
}

const loading = ref(false)
const handleOk = async () => {
  loading.value = true
  try {
    await setRoleMenuApi(Record.value.id, {
      menuIds: checked.value,
    })
    open.value = false
    emits('editOk')
  } finally {
    loading.value = false
  }
}

defineOptions({
  name: 'EditDictModal',
})
defineExpose({
  showModal,
})
</script>
